import { PropType, defineComponent } from "vue";
import Progress from "../Progress";

export interface WordCountProps {
    total: number;
    value: string;
    prefix?: any;
    prefixOverflow?: any;
    suffix?: any;
    suffixOverflow?: any;
    circle?: boolean;
    overflow?: boolean;
    radius?: number;
}

export default defineComponent({
    name: 'WordCount',
    props: {
        total: {type: Number as PropType<WordCountProps['total']>, default: 0},
        value: {type: String as PropType<WordCountProps['value']>, default: ''},
        prefix: {type: String as PropType<WordCountProps['prefix']>, default: ''},
        prefixOverflow: {type: String as PropType<WordCountProps['prefixOverflow']>, default: ''},
        suffix: {type: String as PropType<WordCountProps['suffix']>, default: ''},
        suffixOverflow: {type: String as PropType<WordCountProps['suffixOverflow']>, default: ''},
        circle: {type: Boolean as PropType<WordCountProps['circle']>, default: false},
        overflow: {type: Boolean as PropType<WordCountProps['overflow']>, default: false},
        radius: {type: Number as PropType<WordCountProps['radius']>, default: 10}
    },
    setup (props) {
        const overflow = () => {
            const val = props.value ?? '';
            return val.length > props.total;
        };
        const overNumber = () => {
            const val = props.value ?? '';
            return props.overflow && overflow() ? val.length - props.total : val.length;
        };
        const percent = () => {
            const val = props.value ?? '';
            return Math.min(val.length / props.total * 100, 100);
        };
        const radius = props.radius ?? 10;
        return () => <div class="cm-word-count">
            {
                props.circle ?
                    <Progress type="circle" radius={radius} strokeWidth={1} hidePercent value={percent()}/>
                    : <>
                        <span class={{"cm-word-count-prefix": true, 'cm-word-count-overflow': overflow()}}>
                            {overflow() ? props.prefixOverflow : props.prefix}
                        </span>
                        <span class={overflow() ? 'cm-word-count-overflow' : ''}>{overNumber()}</span>
                        <span>/</span>
                        <span>{props.total}</span>
                        <span class={{"cm-word-count-suffix": true, 'cm-word-count-overflow': overflow()}}>{overflow() ? props.suffixOverflow : props.suffix}</span>
                    </>
            }
        </div>;
    },
});
